import EssayCommentCard from '@/components/EssayCommentCard';
import MyCard from '@/components/MyCard';
import MyPageContainer from '@/components/MyPageContainer';
import CardList from '@/pages/serviceProject/components/CardList';
import { addOrderInfoUsingPost } from '@/services/backend/orderInfoController';
import {
  doServiceProjectClickUsingGet,
  getServiceProjectVoByIdUsingGet,
} from '@/services/backend/serviceProjectController';
import { history, useRequest } from '@umijs/max';
import { Button, Card, Checkbox, Col, Flex, Form, message, Row, Typography } from 'antd';
import { FormProps } from 'antd/lib';
import { MdCatalog, MdPreview } from 'md-editor-rt';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import useStyles from './style.style';
import { listBisheProjectVoByPageUsingPost } from '@/services/backend/bisheProjectController';

//等待时间
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

interface PayChoiceProps {
  serviceProjectVO: API.ServiceProjectVO;
}

//支付node
const PayChoice: React.FC<PayChoiceProps> = (props) => {
  const { serviceProjectVO } = props;
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);

  type FieldType = {
    protocol?: string;
  };

  /**
   * 处理订单支付
   * @param serviceProjectVO
   */
  const handleOrder = async (serviceProjectVO: API.ServiceProjectVO) => {
    setSubmitLoading(true);
    try {
      const res = await addOrderInfoUsingPost({
        name: serviceProjectVO.title,
        targetId: serviceProjectVO.id,
        type: 'service',
        needDeploy: 1
      });
      if (res.code === 0 && res.data) {
        message.success('下单成功,3s后跳转~');
        await waitTime(3000);
        history.replace(`/serviceProject/order/${res.data}`);
      }
    } catch (e: any) {
      message.error(e.message);
    } finally {
      setSubmitLoading(false);
    }
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    const { protocol } = values;
    if (!protocol) {
      message.error('请阅读平台用户协议、购买协议和隐私政策后勾选同意');
      return;
    }
    // 将选中状态和价格一起传递给处理函数
    handleOrder(serviceProjectVO).then(() => {});
  };

  return (
    <div>
      <Typography.Title level={4} type={'danger'}>
        请选择你要下单的服务
      </Typography.Title>
      <Form name="basic" onFinish={onFinish} autoComplete="off">
        <Typography.Title level={4}>
          总费用：<span className={'text-[#ff4d4f]'}>￥{serviceProjectVO.price}</span>
        </Typography.Title>
        <Flex justify={'center'} className={'mb-1.5'}>
          <Form.Item<FieldType>
            name="protocol"
            valuePropName="checked"
            noStyle={true}
            className={'mb-1.5'}
            label={null}
          >
            <Checkbox>
              我已阅读并同意平台
              <Typography.Link>用户协议</Typography.Link>、
              <Typography.Link>购买协议</Typography.Link>和
              <Typography.Link>隐私政策</Typography.Link>
            </Checkbox>
          </Form.Item>
        </Flex>
        <Flex justify={'center'}>
          <Form.Item label={null} noStyle={true}>
            <Button type={'primary'} htmlType="submit" block={true} loading={submitLoading}>
              下单
            </Button>
          </Form.Item>
        </Flex>
      </Form>
    </div>
  );
};

const Detail: React.FC = () => {
  const { styles } = useStyles();
  const params = useParams();
  const id = (params['id'] ?? -1) as number;
  const scrollElement = document.documentElement;

  const [hotServiceProjects, setHotServiceProjects] = useState<API.ServiceProjectVO[]>([]);

  const { data, loading } = useRequest(() => {
    return getServiceProjectVoByIdUsingGet({ id });
  });

  //获取最热门的前5个项目
  const loadHotServiceProject = async () => {
    const res = await listBisheProjectVoByPageUsingPost({
      sortField: 'clickNum',
      sortOrder: 'descend',
    });
    if (res.code === 0) {
      setHotServiceProjects(res.data?.records?.slice(0, 5) ?? []);
    }
  };

  //初始化页面
  useEffect(() => {
    //浏览数+1
    doServiceProjectClickUsingGet({ serviceProjectId: id });
    loadHotServiceProject();
  }, []);

  //内容node
  const content: React.ReactNode = (
    <>
      <div className={styles.head} style={{ margin: '0 0 16px 0' }}>
        <div className={styles.detailTitle}> {data?.title}</div>
      </div>
      <Row gutter={16}>
        <Col span={18} xs={24} lg={16} xl={17}>
          <Flex vertical={true}>
            <Card variant={'borderless'}>
              <MdPreview id={data?.title} modelValue={data?.introduce} />
            </Card>
            <Card variant={'borderless'} className={'mt-4'}>
              <PayChoice serviceProjectVO={data ?? {}} />
            </Card>
            <div className={'mt-4 mb-4'}>
              <EssayCommentCard id={id} type={'service'} />
            </div>
          </Flex>
        </Col>
        <Col span={6} xs={24} lg={16} xl={7}>
          <Flex vertical={true}>
            <MyCard title={'📖目录'}>
              <MdCatalog
                className={'text-base'}
                editorId={data?.title ?? ''}
                scrollElement={scrollElement}
                scrollElementOffsetTop={80}
              />
            </MyCard>
            <div className={'mt-4'}>
              <MyCard title={'🔥热门项目'}>
                <CardList
                  data={hotServiceProjects}
                  loading={loading}
                  gutter={{
                    gutter: 16,
                    xs: 1,
                    sm: 1,
                    md: 1,
                    lg: 1,
                    xl: 1,
                    xxl: 1,
                  }}
                />
              </MyCard>
            </div>
            <div className={'mt-4'}>
              <MyCard title={'🚀广告位'}>
                <span>广告位招租~</span>
              </MyCard>
            </div>
          </Flex>
        </Col>
      </Row>
    </>
  );

  return <MyPageContainer content={content} loading={loading} />;
};

export default Detail;
